//
//  SearchAddressDictionaryView.swift
//  GreenDeal
//
//  Created by Moennig Q on 28/2/2023.
//

import UIKit
import SnapKit
import RxCocoa
import RxSwift
import RxGesture
import DaisyNet
class SearchAddressView: UIView {
    fileprivate lazy var disposeBag = DisposeBag()
    private var searchValue: String = ""

    var selectClosure: ((PhysicalAddressViewModel)->Void)?
    let searchTopView = SearchTopView(bgImageName: "createjob_installation_address_top_bg")
    
    let tableView = TableView()
    var list = [PhysicalAddressViewModel]()
    //用于延时500ms搜索地址
    var delaySearchTimer: Timer?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpView()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init(defaultSearchValue: String ) {
        super.init(frame: CGRect.zero)
        self.searchValue = defaultSearchValue
        setUpView()
    }
    private func setUpView() {
        self.backgroundColor = .white
        self.searchTopView.searchTextfield.placeholder = R.string.localizable.searchForAnAddress()
        self.addSubview(searchTopView)
        searchTopView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //
        self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView.showsVerticalScrollIndicator = false
        //防止上拉加载时数据滚动
        self.tableView.estimatedRowHeight = 200
        self.tableView.rowHeight = UITableView.automaticDimension
        //
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(SearchAddressCell.self, forCellReuseIdentifier: SearchAddressCell.reuseCellIdentifier)
        
        self.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(searchTopView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        //
        self.searchTopView.cancelLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.removeFromSuperview()
        }).disposed(by: self.disposeBag)
        self.searchTopView.searchTextfield.rx.controlEvent(.editingDidEndOnExit).subscribe { [weak self] _ in
            guard let strongSelf = self else {return }
            guard let searchText = strongSelf.searchTopView.searchTextfield.text , searchText.trimmingCharacters(in: .whitespaces).count >= 4 else {return}
            strongSelf.getAddressListBySearchValue()
        }.disposed(by: self.disposeBag)
        //是否有默认值
        if self.searchValue != ""{
            self.searchTopView.searchTextfield.text = self.searchValue
            self.getAddressListBySearchValue()
        }else{//没有搜索值，直接弹出键盘
            DispatchQueue.main.async {//直接在主队列异步弹出键盘，处理无法正常弹出键盘的问题
                self.searchTopView.searchTextfield.becomeFirstResponder()
            }
        }
        //
        self.searchTopView.editingChangedClosure = {[weak self] in
            guard let strongSelf = self else { return  }
            DaisyNet.cancel(APIConfig.getRequestAPIForV2(APIConfig.GetAddressListAPI))
            strongSelf.delaySearchTimer?.invalidate()  // Cancel any previous timer
            // If the textField contains at least 3 characters…
            let currentText = (strongSelf.searchTopView.searchTextfield.text ?? "").trimmingCharacters(in: .whitespaces)
//            DebugLog(currentText)
            if currentText.count >= 4 {//超过四位才搜索
                 // …schedule a timer for 0.5 seconds
                strongSelf.delaySearchTimer = Timer.scheduledTimer(timeInterval: 0.5, target: strongSelf, selector: #selector(strongSelf.getAddressListBySearchValue), userInfo: nil, repeats: false)
            }else{//少于4位，显示空白
                strongSelf.list.removeAll()
                strongSelf.tableView.reloadData()
            }
        }
        
        tableView.loadFaildView.retryBtn.addTarget(self, action: #selector(retryBtnClick), for: UIControl.Event.touchUpInside)
    }
    
    @objc private func retryBtnClick(){
        self.getAddressListBySearchValue()
    }
    @objc func closeBtnClick(){
        self.removeFromSuperview()
    }
    
    
    //MARK: - 根据search value获取address list
    @objc private func getAddressListBySearchValue(){
        self.searchValue = (self.searchTopView.searchTextfield.text ?? "").trimmingCharacters(in: .whitespaces)
        let vm = DictionaryService()
        vm.setBlockAfterNetwork { [weak self] (result, _) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideLoadingView()
            strongSelf.list.removeAll()
            if let list = result as? Array<PhysicalAddressViewModel>{
                strongSelf.list = list
                strongSelf.tableView.reloadData()
            }
            //没有数据显示not data view，有数据隐藏not data view
            strongSelf.tableView.showResultView(nodataFlag: (strongSelf.list.count == 0 ? true : false),tipMsg: R.string.localizable.noMatchedAddress())
        } errorBlock: { [weak self] (code, error) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideLoadingView()
            strongSelf.endEditing(true)
            strongSelf.list.removeAll()
            strongSelf.tableView.reloadData()
            strongSelf.tableView.showRetryView()
            Tool().showAlertViewWithOneBtn(message: error)
        }
        ModelViewUtil.shared.showLoadingView(parentView: self)
        vm.getAddressList(self.searchValue)
    }
}


extension SearchAddressView: UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: SearchAddressCell.reuseCellIdentifier) as? SearchAddressCell
        if cell == nil {
            cell = SearchAddressCell(style: .default, reuseIdentifier: SearchAddressCell.reuseCellIdentifier)
        }
        cell!.setData(self.list[indexPath.row].full_address)
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectClosure?(self.list[indexPath.row])
        self.removeFromSuperview()
    }
    //
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.getAddressListBySearchValue()
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.endEditing(true)
        return true
    }
}
